<template>
  <div>
    <el-button @click="connection">连接服务器</el-button>
    <el-button @click="closeconnect">断开连接</el-button>
    <el-input type="text"></el-input>
    <el-button @click="sendmsg">发送</el-button>
  </div>
</template>
<script>
  import SockJS from 'sockjs-client';
  import Stomp from 'stompjs';

  let stompClient;
  let url = "ws://127.0.0.1:1470/stomp";
  export default {
    name: "Chat",
    data() {
      return {
        timer: '',
        headers: {
          login: '张三',
          passcode: '',
          'client-id': 'stomp-client-id',
          message: "headers的message"
        },
      }
    },
    methods: {
      sendmsg() {
        //console.log(stompClient.ws.readyState);
        let flag = stompClient.ws.readyState;
        switch (flag) {
          case (undefined):
            alert("请连接服务器");
            break;
          case(1):
            stompClient.send("/queue/greetings", {}, JSON.stringify({id: 101, name: "李四"}));
            break;
          case(3):
            alert("请连接服务器");
            break;
        }
      }
      ,
      connection() {
        //console.log(stompClient);
        // 建立连接对象
        // 获取STOMP子协议的客户端对象
        if (stompClient !== "undefined") {
          stompClient = Stomp.client(url);
          // 建立连接
          // console.log(stompClient.ws.readyState);
          stompClient.connect(this.headers, this.connect_callback, this.error_callback);
        } else {
          alert("已连接，无需重复连接");
        }
      }
      ,
      // 断开连接
      closeconnect() {
        if (stompClient.ws.readyState) {
          stompClient.disconnect();
        } else {
          stompClient = "";
        }
      }
      ,
      connect_callback() {
        let payload = JSON.stringify({'message': 'greeting to stomp broker!'});
        stompClient.send("/app/message", {}, payload);
        // 完成连接后订阅
        if (stompClient.ws.readyState !== 0) {
          stompClient.subscribe('/topic/subscribe', function (message) {
            console.log('subscribe topic callback:' + message.body);
          });
        }
      }
      ,
      error_callback() {
        alert(error.headers.message);
      }
      ,
    },
  }
</script>

<style scoped>

</style>
